package com.loyal.mwm.ext

import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.text.TextUtils
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.text.style.UnderlineSpan
import androidx.core.text.HtmlCompat
import com.base.kit.ResUtil

fun CharSequence?.replaceNull(): String {
    return ResUtil.replaceText(this)
}

fun CharSequence?.nullToDefault(defValue: String = ""): CharSequence {
    return if (null == this || TextUtils.isEmpty(this)) defValue else this
}

fun SpannableString.link(linkText: String, click: ClickableSpan): SpannableString {
    val index = indexOf(linkText)
    if (-1 == index)
        return this
    val end = index + linkText.length
    val textColor = Color.parseColor("#3F51B5")
    setSpan(
        UnderlineSpan(),
        index, end,
        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
    )
    setSpan(click, index, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    setSpan(
        ForegroundColorSpan(textColor), index,
        end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
    )
    return this
}

fun String.fromHtml(): CharSequence {
    return HtmlCompat.fromHtml(this, HtmlCompat.FROM_HTML_MODE_LEGACY)
}

/**
 * @param suffix 后
 */
fun String.startFromHtml(
    end: String?, color: String = "black",
    newLine: Boolean = false
): CharSequence {
    val source = String.format(
        "<font color='%s'>%s</font>%s%s",
        this,
        color,
        end,
        if (newLine) "<br>" else ""
    )
    return source.fromHtml()
}

fun String.endFromHtml(
    end: String?, color: String = "red",
    newLine: Boolean = false
): CharSequence {
    val source = String.format(
        "%s<font color='%s'>%s</font>%s", this, color, end,
        if (newLine) "<br>" else ""
    )
    return source.fromHtml()
}

fun String.endFromHtml2(start: String?, end: String?, color: String = "#99B9FF") {
    /*if (!color.startsWith("#")) {
            color = "#" + color;
        }*/
    val source = String.format("%s<font color='%s'>%s</font>", start, color, end)
    source.fromHtml()
}